//
//  ZoomScrollView.m
//  Qianbancaifu
//
//  Created by SYLH on 16/1/11.
//  Copyright © 2016年 SYLH. All rights reserved.
//

#import "ZoomScrollView.h"

@interface ZoomScrollView ()<UIGestureRecognizerDelegate>

@property (nonatomic,assign) CGRect originalRect;

@property (nonatomic,assign) CGPoint translation;

@property (nonatomic,assign) long dragSpeedY;

@property (nonatomic,assign) double zoomValue;

@end

@implementation ZoomScrollView

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        
        self.backgroundColor = [UIColor clearColor];
        
        _scrollView =[[ UIScrollView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds))];
        [_scrollView setContentSize:CGSizeMake(CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds))];
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.bounces = NO;
        _scrollView.delegate = self;
        _scrollView.backgroundColor = [UIColor clearColor];
        _scrollView.maximumZoomScale = 3.0;
        _scrollView.minimumZoomScale = 1.0;
        _scrollView.clipsToBounds = YES;
        [self addSubview:_scrollView];
        
        UIPanGestureRecognizer * panGes = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(processPanGes:)];
        panGes.delegate = self;
        [self addGestureRecognizer:panGes];
        
        _imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(_scrollView.bounds), CGRectGetHeight(_scrollView.bounds))];
        _imgView.backgroundColor = [UIColor clearColor];
        _imgView.contentMode = UIViewContentModeScaleAspectFill;
        _imgView.clipsToBounds = YES;
        [_scrollView addSubview:_imgView];
        
        
        
    }
    return self;
}

-(void)setImageModel:(FullScreenImage *)imageModel
{
    _imageModel = imageModel;
    self.imgView.frame = CGRectMake(0, 0, CGRectGetWidth(self.scrollView.bounds), CGRectGetHeight(self.scrollView.bounds));
    self.scrollView.zoomScale = 1.0;
    
    //1.存在大图，直接加载
    if (imageModel.fullImage) {
        self.imgView.image = imageModel.fullImage;
        [self setImageShowViewFrame:self.imgView image:self.imgView.image];
    }
    //2.加载网络图片
    else if (imageModel.fullImagePath){
        
        //SD 本地查找缓存
        SDWebImageManager * manager = [SDWebImageManager sharedManager];
        if ([manager cachedImageExistsForURL:[NSURL URLWithString:imageModel.fullImagePath]]) {
            self.userInteractionEnabled = YES;
            [self stopLoadingAnimation];
        }else{
            self.userInteractionEnabled = NO;
            [self startLoadingAnimation];
        }
        
        [self setImageShowViewFrame:self.imgView image:imageModel.placeholderImage];
        @weakify(self);
        [self.imgView sd_setImageWithURL:[NSURL URLWithString:imageModel.fullImagePath]
                            placeholderImage:imageModel.placeholderImage
                                     options:SDWebImageRetryFailed
                                   completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                                       @strongify(self);
                                       self.userInteractionEnabled = YES;
                                       [self stopLoadingAnimation];
                                       
                                   }];
    }
    
}

-(void)setImageShowViewFrame:(UIImageView *)imageView image:(UIImage *)image
{
    UIImage * showImage = image;
    CGFloat imageW = showImage.size.width;
    CGFloat imageH = showImage.size.height;
    
    CGFloat newImageW = KScreen_Width;
    CGFloat newImageH = KScreen_Width / imageW * imageH;
    
    imageView.frame = CGRectMake(0, 0, newImageW, newImageH);
    //图片宽高比例大于屏幕比例 -> 长图
    if (newImageH > KScreen_Height) {

    }else{
        imageView.center = imageView.superview.center;
    }
    
    
}

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return self.imgView;
}

-(void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale
{
    [scrollView setZoomScale:scale animated:NO];
}


#pragma mark- scroll 让图片居中
- (void)scrollViewDidZoom:(UIScrollView *)scrollView
{
        CGFloat offsetX = (scrollView.bounds.size.width > scrollView.contentSize.width)?
        (scrollView.bounds.size.width - scrollView.contentSize.width) * 0.5 : 0.0;
        
        CGFloat offsetY = (scrollView.bounds.size.height > scrollView.contentSize.height)?
        (scrollView.bounds.size.height - scrollView.contentSize.height) * 0.5 : 0.0;
        
        self.imgView.center = CGPointMake(scrollView.contentSize.width * 0.5 + offsetX,
                                              scrollView.contentSize.height * 0.5 + offsetY);

}



-(void)startLoadingAnimation
{
    [self stopLoadingAnimation];
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self  animated:YES];
    hud.mode = MBProgressHUDModeIndeterminate;
    hud.color = [UIColor colorWithWhite:0.0 alpha:0.0];
}

-(void)stopLoadingAnimation
{
    [MBProgressHUD hideHUDForView:self animated:YES];
}

#pragma mark - 手势
// 给加的手势设置代理, 并实现此协议方法
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
    BOOL canPanGes = NO;
    
    if ([gestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]]) {
    
        UIPanGestureRecognizer *pan = (UIPanGestureRecognizer *)gestureRecognizer;
        CGPoint translation = [pan translationInView:pan.view];
        
        //图片超出屏幕时
        if (self.scrollView.contentSize.height > KScreen_Height) {
            if (translation.y > 0 && translation.y > fabs(translation.x) && self.scrollView.contentOffset.y <= 0) {
                canPanGes = YES;
            }else if (translation.y < 0 && fabs(translation.y) > fabs(translation.x) && self.scrollView.contentOffset.y + 1 >= self.scrollView.contentSize.height - KScreen_Height){
                canPanGes = YES;
            }else{
                canPanGes = NO;
            }
        }else{
            if (fabs(translation.y) > fabs(translation.x) ) {
                canPanGes = YES;
            }else{
                canPanGes = NO;
            }
        }
    }
    self.scrollView.scrollEnabled = !canPanGes;
    
    return canPanGes;
}

-(void)processPanGes:(UIPanGestureRecognizer *)recognizer
{
    if (recognizer.state == UIGestureRecognizerStateBegan) {
        self.originalRect = recognizer.view.frame;
    }else if (recognizer.state == UIGestureRecognizerStateChanged) {
        
        self.translation = [recognizer translationInView:recognizer.view];
        self.dragSpeedY = [recognizer velocityInView:recognizer.view].y;
        
        CGPoint newCenter = CGPointMake(recognizer.view.center.x + self.translation.x,
                                        recognizer.view.center.y + self.translation.y);
        
        //改变大小
        //最小缩小到当前的 1/2;
        double dragValue = fabs(newCenter.y - self.originalRect.size.height * 0.5);
        self.zoomValue = 1.0 - dragValue / KScreen_Height * 0.4;
        if (self.zoomValue < 0.5) {
            self.zoomValue = 0.5;
        }
        recognizer.view.transform = CGAffineTransformMakeScale(self.zoomValue, self.zoomValue);
        
        //改变中心点
        recognizer.view.center = newCenter;
        [recognizer setTranslation:CGPointZero inView:recognizer.view];
        
        if ([self.delegate respondsToSelector:@selector(dragShowImageViewWithDragValue:)]) {
            [self.delegate dragShowImageViewWithDragValue:dragValue];
        }
        
    }else if(recognizer.state == UIGestureRecognizerStateEnded){
        
        //拖动速度小于100 恢复之前的状态
        if (labs(self.dragSpeedY) < 1000) {
            [self setOriginalFremeWithView:recognizer.view complete:nil];
            
            if ([self.delegate respondsToSelector:@selector(loosenShowImageView)]) {
                [self.delegate loosenShowImageView];
            }
        }else{
            //让界面消失
            if ([self.delegate respondsToSelector:@selector(fastDragShowImageViewWithRect:transValue:)]) {
                
                UIWindow * window=[[[UIApplication sharedApplication] delegate] window];
                CGRect windowRect = [self.imgView convertRect:self.imgView.bounds toView:window];
                
                [self.delegate fastDragShowImageViewWithRect:windowRect transValue:self.zoomValue];
            }
        }
    }
}

-(void)setOriginalFremeWithView:(UIView *)view complete:(void(^)())complete
{
    [UIView animateWithDuration:0.2 delay:0.0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        self.transform = CGAffineTransformMakeScale(1.0, 1.0);
        view.frame = self.originalRect;
    } completion:^(BOOL finished) {
        if (complete) {
            complete();
        }
    }];
}

@end
